import React, {Component, createRef} from 'react';
// import styles from './index.module.scss'
import WPaging, { PageInterface, PageingRefInterface } from '../../../../components/paging'
import StudyModel from '../../../../models/studyModel'
import TableView from '../../../../components/tableView/fixed'
import { withRouter, RouteComponentProps } from 'react-router-dom'
import SearchBar, { ChangeTypeInterface as SearchBarType } from '../../../../components/searchBar'

interface StateInterface {
  dataArr: Array<StudyModel>
  types: Array<string>,
  total: number
}

interface PropsInterface extends RouteComponentProps {
}

interface QueryListInterface extends PageInterface, SearchBarType {

}

class WebStudyList extends Component<PropsInterface, StateInterface> {

  state: Readonly<StateInterface> = {
    dataArr: [],
    types: [],
    total: 0
  }

  pageingRef = createRef<PageingRefInterface>()

  listQuery: Partial<QueryListInterface> = {}

  searchBarOptions = ['所有', '标题', '描述', '内容']

  constructor(props: PropsInterface) {
    super(props)

    this.pageChange = this.pageChange.bind(this)
    this.searchBarChange = this.searchBarChange.bind(this)
    this.cellClick = this.cellClick.bind(this)
  }

  componentDidMount() {
    this.getTypes()
  }

  loadData() {
    StudyModel.getModels(this.listQuery).then((data: any) => {
      this.setState(() => {
        return {
          dataArr: data.list,
          total: data.total
        }
      })
    }).catch(() => {})
  }

  pageChange(query: PageInterface) {
    this.listQuery = {
      ...this.listQuery,
      ...query
    }
    this.loadData()
  }

  searchBarChange(query: SearchBarType) {
    this.listQuery = {
      ...this.listQuery,
      ...query
    }
    this.pageingRef.current!.reload()
  }

  getTypes() {
    StudyModel.getTypes().then((data: any) => {
      this.setState(() => {
        return {
          types: data
        }
      })
    }).catch(() => {})
  }

  cellClick(item: StudyModel) {
    this.props.history.push(`/web/study/detail?id=${item._id}`)
  }

  render(): React.ReactElement<any, string | React.JSXElementConstructor<any>> | string | number | {} | React.ReactNodeArray | React.ReactPortal | boolean | null | undefined {
    return (
      <div className={ 'w-content-box' }>
        <SearchBar searchTypes={this.searchBarOptions} onChange={ this.searchBarChange } navItems={ this.state.types } />
        <TableView 
          cellClick={ this.cellClick }
          centerTextKey='dateStr' 
          bottomTextKey='describe'
          titleKey='title' 
          iconKey='pcListIconUrl' 
          models={ this.state.dataArr }
        />
        <WPaging ref={ this.pageingRef } onChange={ this.pageChange } total={ this.state.total }/>
      </div>
    );
  }
}

export default withRouter<PropsInterface>(WebStudyList);
